<template>
    <div class="components-container">
        <div class="header-form">
          <div class="layui-inline" v-if="!choosetime">
            <label class="layui-form-label">经办日期</label>
            <div class="layui-inline">
             <el-radio-group v-model="selectDataExtend.regDateValue" @change="search">
              <el-radio-button  :label="DateSelectMode.now" class="radio">当日</el-radio-button>
              <el-radio-button  :label="DateSelectMode.all" class="radio">全部</el-radio-button>
             </el-radio-group>
            </div>
          </div>
          <!-- 义乌的 -->
          <div class="layui-inline" v-if="choosetime">
            <label class="layui-form-label">处理日期</label>
            <div class="layui-inline">
             <el-radio-group v-model="selectDataExtend.regDateValue" @change="search">
              <el-radio-button  :label="DateSelectMode.now" class="radio">当日</el-radio-button>
              <el-radio-button  :label="DateSelectMode.all" class="radio">全部</el-radio-button>
             </el-radio-group>
            </div>
          </div>
          <div class="layui-inline" >
            <label class="layui-form-label">结账状态</label>
            <div class="layui-inline">
             <el-radio-group v-model="selectDataExtend.ChdstatusEquals" @change="search">
              <el-radio-button  :label="DateSelectMode.now" class="radio">全部</el-radio-button>
              <el-radio-button  :label="DateSelectMode.future" class="radio">已结账</el-radio-button>
              <el-radio-button  :label="DateSelectMode.all" class="radio">未结账</el-radio-button>
             </el-radio-group>
            </div>
          </div>
           <div class="layui-inline" >
                <label class="layui-form-label">业务编号</label>
                 <div class="layui-inline">
                    <el-input v-model="selectData.RegbussnumLike" placeholder="请输入业务编号" @keydown.enter.native="search"></el-input>
                 </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" >零售日期</label>
                <el-date-picker v-date v-model="selectData.ChddateGreaterAndEquals" type="date" placeholder="选择日期范围" @change="search">
                </el-date-picker>
                <el-date-picker v-date v-model="selectData.ChddateLessAndEquals" type="date" placeholder="选择日期范围" @change="search">
                </el-date-picker>
            </div>
            <div class="layui-inline" v-if="showname" style="width:300px">
                 <label class="layui-form-label">逝者姓名</label>
                 <div class="layui-inline">
                    <el-input v-model="selectData.RegnameLike" placeholder="请输入逝者姓名" @keydown.enter.native="search"></el-input>
                 </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">客户姓名</label>
              <div class="layui-inline">
                <el-input v-model="selectData.ReghandnameLike" placeholder="请输入客户姓名" @keydown.enter.native="btnSearch"></el-input>
              </div>
            </div>
            <el-button type="primary" @click="search" :loading="this.$store.state.isloading">搜索</el-button>
            <el-button  @click="btnRepeat" >重置</el-button>
        </div>
        <div style="height:56px;margin-top:5px">
            <ul class="toolList">
              <li><el-button type="primary" @click="btnSearch" :loading="this.$store.state.isloading">刷新</el-button></li>
                <li v-if="btnShow(item.BTNVALUE)" v-for="(item, index) in $store.state.btnListCommon" @click="operate(item.BTNVALUE)">
                  <el-button type="primary" :value="item.BTNSHOWNAME" v-text="item.BTNSHOWNAME"></el-button>
                </li>
            </ul>
        </div>
        <dataTable :headList="headList" :dataList="dataList" :pageOrder="pageOrder" @pageChange="pageChange" @selectRow="selectRow"></dataTable>
       <checkout-add ref="checkoutAdd" @refreshData="getData"></checkout-add>
       <printmodal ref="printPdf"></printmodal>
    </div>
</template>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/common.scss";
.el-button + .el-button {
  margin-left: 0;
}
.btnCenter {
  text-align: center;
}
</style>
<script>
import sweetModal from "@/components/sweetModal";
import dataTable from "@/components/Table/DataTable";
import checkoutAdd from "./checkoutAdd";
import apiBase from "@/api/apiBase.js";
import { formatDate, timeStringToDate } from "@/utils/date.js";
import { manage } from "@/mixins/managePage.js";
import { ORDER } from "@/const/orderConst.js";
import { DATESELECTMODE } from "@/const/const.js";
import printmodal from "@/components/Pdf/Print";
import axios from 'axios'
const ADD = "新增";
const MODIFY = "调整收费项目";
const INFO = "详情";
const CHECKOUT = "结账";
const CANCEL = "取消结账";
const DELETE = "删除";
const INVALID = "作废";
const RetailList = "打印零售清单";
const DOTXT = "生成发票信息"; //宁波
const BILL = "挂账";


const WJZ = "A";
const YJZ = "B";
const YZF = "C";
const YGZ = "D";
const HZ = "E";

export default {
  name: "retail",
  mixins: [manage],
  data() {
    return {
      DateSelectMode: DATESELECTMODE,
      //查询条件
      selectData: {},
      selectDataExtend: {
        regDateValue: null,
        ChdstatusEquals: null,
        ChddateGreaterAndEquals: null,
        ChddateLessAndEquals: null,
      },
      //收费信息
      chdData: {},
      CHDCODNAME: null,
      chlList: [],
      dataLists: [],
      message: 0,
      iscopysfqd: null,
      ischangered: null,
      ischangnb: null,
      choosetime: null,
      showname: null,
      showalldatas:null,
    };
  },
  methods: {
    //获取表头
    getColumns() {
      let data = {};
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Column.GetCheckoutLsColumns,
        res => {
          this.headList = res.data.content;
        }
      );
    },
    //获取收费信息
    getData() {
      let selectData = JSON.parse(JSON.stringify(this.selectData));
      selectData.ChddateLessAndEquals = formatDate(
        selectData.ChddateLessAndEquals,
        "yyyyMMdd"
      );
      selectData.ChddateGreaterAndEquals = formatDate(
        selectData.ChddateGreaterAndEquals,
        "yyyyMMdd"
      );
      if (!this.selectData.RegbussnumLike) {
        selectData.RegbussnumLike = null;
      }
      if (!this.selectData.RegnameLike) {
        selectData.RegnameLike = null;
      }
      let data = {
        PageIndex: this.pageOrder.currentPage,
        PageSize: this.pageOrder.pageSize,
        OrderBy: this.pageOrder.orderType,
        OrderByType: this.pageOrder.orderSort,
        Data: selectData
      };
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Checkout.RetailQuery,
        res => {
          this.dataList = res.data.content.OutData;
          this.pageOrder.totalNum = res.data.content.RecordCount;
          this.dataList.forEach(data => {
            data.REGDATE = data.REGDATE.substring(0, 16);
            data.CHDDATE = data.CHDDATE.substring(0, 16);
          });
          this.$nextTick(function() {
            let rows = document.getElementsByClassName("el-table__row");
            if(this.ischangered){
              this.dataList.forEach((item,index) => {
                  rows[index].style.color = '#606266';
                  if(item.REGCRETYPE === 'A'){
                      rows[index].style.color = 'red';
                  }
              });
            };
            if(this.ischangnb){
              this.dataList.forEach((item,index) => {
                  rows[index].style.color = '#606266';
                  if(item.REGCRETYPE === 'A'||item.REGCRETYPE === 'C'){
                      rows[index].style.color = '#007eff';
                  }
                  if(item.REGCRETYPE === 'D'){
                      rows[index].style.color = 'red';
                  }
              });
            };
          });
        }
      );
    },
    getallData() {
      let selectData = JSON.parse(JSON.stringify(this.selectData));
      selectData.ChddateLessAndEquals = formatDate(
        selectData.ChddateLessAndEquals,
        "yyyyMMdd"
      );
      selectData.ChddateGreaterAndEquals = formatDate(
        selectData.ChddateGreaterAndEquals,
        "yyyyMMdd"
      );
      if (!this.selectData.RegbussnumLike) {
        selectData.RegbussnumLike = null;
      }
      if (!this.selectData.RegnameLike) {
        selectData.RegnameLike = null;
      }
      let data = {
        PageIndex: -1,
        PageSize: 0,
        OrderBy: this.pageOrder.orderType,
        OrderByType: this.pageOrder.orderSort,
        Data: selectData
      };
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Checkout.RetailQuery,
        res => {
          this.dataLists = res.data.content.OutData;
          this.pageOrder.totalNum = res.data.content.RecordCount;
          this.dataLists.forEach(data => {
            data.REGDATE = data.REGDATE.substring(0, 16);
            data.CHDDATE = data.CHDDATE.substring(0, 16);
          });
          var s = 0;
          for(var i in this.dataLists){
            var num = Number(this.dataLists[i].CHDRECEIVED);
            s = num + s;
          };
          this.message = s;
          this.dataLists.push({CHDSTATUSDESC: "合计",CHDRECEIVED: this.message});
        }
      );
    },
    //导出
    exportExcel() {
      if (this.dataList.length === 0){
          this.$message.error("无导出数据！");
          return;
      }
      this.downloadLoading = true;
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/vendor/Export2Excel");
        export_json_to_excel(this.headList, this.dataLists, '零售管理');
        this.downloadLoading = false;
      });
    },
    search(){
      this.getData();
      this.getallData();
      this.$store.state.isloading = true;
    },
    //功能操作
    operate(order) {
      this.order = order;
      this.dataRepeat();
      switch (this.order) {
        case ADD:
          this.dataAdd();
          break;
        case MODIFY:
          this.dataModify();
          break;
        case INFO:
          this.dataInfo();
          break;
        case DOTXT:          //宁波生成开票信息
          this.documenttext()
          break;  
        case CHECKOUT:
          this.$refs.checkoutAdd.open(ORDER.RETCHECKOUT, this.currentRow.CHDID, '2');
          break;
        case CANCEL:
          this.chdCancel();
          break;
        case BILL:
          this.chdBill();
          break;
        case '取消挂账':
          this.CancelBill();
          break;
        case DELETE:
          this.chdDelete();
          break;
        case INVALID:
          this.chdInvalid();
          break;
        case RetailList:
          this.$refs.printPdf.open(this.order, this.currentRow.CHDID);
          break;
        case '导出':
          this.exportExcel();
          break;
        case '打印发票'://打印发票
          this.$refs.printPdf.open(this.order, this.currentRow.CHDID);
          break;
        default:
      }
    },
       //下载txt 发票 （宁波）
      downloadWithBlob(txt) {
        axios({
            url: "http://127.0.0.1:8080/",
            method: "POST",
            data: { data: txt },
            headers: { "Content-Type": "text/plain" }
          })
            .then(res => {
              if (res.data.Success) {
              console.log("生成文件成功!");
              } else {
                console.log(res.data.ErrMsg);
              }
            })
            .catch(function(error){
                       alert("连接操作插件失败")
                    });
        },
    documenttext(){
      let data = {
        CHDID: this.currentRow.CHDID,
      };
      apiBase.DoService(data, apiBase.getApiAdress().Checkout.GetInvoice, res => {
          if(res.data.content.strReturn){
            let piao=res.data.content.strReturn;
            this.downloadWithBlob(piao);　　// 调用成功
            }
      });
    },
    //零售新增
    dataAdd() {
      this.$refs.checkoutAdd.open(ORDER.ADD);
    },
    //收费信息修改
    dataModify() {
      this.$refs.checkoutAdd.open(ORDER.RETMODIFY, this.currentRow.CHDID);
    },
    //提交
    submit() {
      switch (this.order) {
        case CHECKOUT:
          this.chdCheckout();
          break;
        default:
      }
    },
    //收费详情
    dataInfo() {
      this.$refs.checkoutAdd.open(ORDER.RETAILINFO, this.currentRow.CHDID);
    },
    //取消结账
    chdCancel() {
      this.$confirm("确认是否取消结账?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(callback => {
          let data = {
            CHDID: this.currentRow.CHDID
          };
          apiBase.DoService(
            data,
            apiBase.getApiAdress().Checkout.CancelCheckout,
            res => {
              this.$message({
                type: "success",
                message: "取消结账成功!"
              });
              this.getData();
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //取消结账
    chdDelete() {
      this.$confirm("确认是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(callback => {
          let data = {
            CHDID: this.currentRow.CHDID
          };
          apiBase.DoService(
            data,
            apiBase.getApiAdress().Checkout.Delete,
            res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getData();
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //作废
    chdInvalid() {
      this.$confirm("确认是否作废?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(callback => {
          let data = {
            CHDID: this.currentRow.CHDID
          };
          apiBase.DoService(
            data,
            apiBase.getApiAdress().Checkout.Invalid,
            res => {
              this.$message({
                type: "success",
                message: "作废成功!"
              });
              this.getData();
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //挂账
    chdBill() {
      this.$confirm("确认是否挂账?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(callback => {
          let data = {
            CHDID: this.currentRow.CHDID
          };
          apiBase.DoService(data, apiBase.getApiAdress().Checkout.Bill, res => {
            this.$message({
              type: "success",
              message: "挂账成功!"
            });
            this.getData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //取消挂账
    CancelBill() {
      this.$confirm("确认是否取消挂账?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(callback => {
          let data = {
            CHDID: this.currentRow.CHDID
          };
          apiBase.DoService(
            data,
            apiBase.getApiAdress().Checkout.CancelBill,
            res => {
              this.$message({
                type: "success",
                message: "取消挂账成功!"
              });
              this.getData();
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //查询条件重置
    btnRepeat() {
      this.selectData = {};
      this.initSeachdata();
      this.getData();
    },
    dataRepeat() {
      this.chdData = {};
    },
    //按钮显隐
    btnShow(btn) {
      let status = null;
      if (this.currentRow) {
        status = this.currentRow.CHDSTATUS;  
      }
      switch (btn) {
        case ADD:
          return true;
          break;
        case MODIFY:
          return status === WJZ || status === YGZ;
          break;
        case INFO:
          return status;
          break;
        case CHECKOUT:
          return status === WJZ || status === YGZ;
          break;
        case CANCEL:
          return status === YJZ;
          break;
        case DELETE:
          return status === WJZ;
          break;
        case INVALID:
          return status === YJZ;
          break;
        case BILL:
          return status === 'A';
          break;
        case '取消挂账':
          return status === "D";
          break;
        case RetailList:
          if(this.iscopysfqd){
            return true
          }else{
            return status === YJZ
          }
          break;
        case '导出':
          return true;
          break;
        case '打印发票'://打印发票
          if(status == "B")
          return true;
          break;
        case DOTXT:
          return status === YJZ;//宁波 开票信息下载
          break;  
        default:
      }
    },
    //关闭
    checkoutClose() {
      this.$refs.checkout.close();
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 3) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "N/A";
        }
        if (index < 4) {
          sums[index] = "";
        }
      });
      return sums;
    },
    initSeachdata() {
      if(this.showalldatas){
      this.selectDataExtend.regDateValue = DATESELECTMODE.all;
      this.selectData.ChdchkdateEquals = null;
      this.selectData.ChddateEquals = null;
      }
      else{
        this.selectDataExtend.regDateValue = DATESELECTMODE.now;
        this.selectDataExtend.ChdstatusEquals = DATESELECTMODE.now;
        if(this.choosetime == true){
          this.selectData.ChddateEquals = formatDate(new Date(), "yyyyMMdd");
        }else{
          this.selectData.ChdchkdateEquals = formatDate(new Date(), "yyyyMMdd");
        }
      }  
    }
  },
  components: {
    sweetModal,
    dataTable,
    checkoutAdd,
    printmodal
  },
  activated() {
     apiBase.DoService({},apiBase.getApiAdress().Param.GetIsUseCHDChkdateOrCHDdate,res => {
        this.choosetime = res.data.content; 
        this.initSeachdata();
        this.getData();
        this.getallData();
    });
  },
  mounted() {},
  created() {
    apiBase.DoService({},apiBase.getApiAdress().Param.GetIsShowAllCheckout,res => {
    this.showalldatas = res.data.content; 
    });  //上虞 显示全部搜索
    apiBase.DoService({},apiBase.getApiAdress().Param.GetIsDataTableReddening,res => {
        this.ischangered = res.data.content; 
    });
    apiBase.DoService({},apiBase.getApiAdress().Param.GetIsCreChangeRed,res => {
        this.ischangnb = res.data.content; 
    });
    apiBase.DoService({},apiBase.getApiAdress().Param.GetIsShowName,res => {
        this.showname = res.data.content; 
    });
    this.getColumns();
    apiBase.DoService({},apiBase.getApiAdress().Param.GetNoconditionPrint,res => {
            this.iscopysfqd = res.data.content; 
    });
  },
  watch: {
    "selectDataExtend.regDateValue": function(val) {
      this.selectData.ChdchkdateEquals = null;
      this.selectData.ChddateEquals = null;
      switch (val) {
        case DATESELECTMODE.now:
          if(this.choosetime == true){    
            this.selectData.ChddateEquals = formatDate(new Date(), "yyyyMMdd");
          }else{
            this.selectData.ChdchkdateEquals = formatDate(new Date(), "yyyyMMdd");
          }
          break;
        default:
          break;
      }
    },
    "selectDataExtend.ChdstatusEquals": function(val) {
      switch (val) {
        case DATESELECTMODE.now:
          this.selectData.ChdstatusEquals = null;
          break;
        case DATESELECTMODE.all:
          this.selectData.ChdstatusEquals = "A";
          break;
        case DATESELECTMODE.future:
          this.selectData.ChdstatusEquals = "B";
          break;
        default:
          break;
      }
    },
  }
};
</script>

